<template>
  <view class="schedule-container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="nav-section" @click="prevWeek">
        <uni-icons type="left" size="20" color="#666666" />
        <text>上一周排课</text>
      </view>
      <view class="title-section">
        <text class="main-title">{{ classInfo.name ? classInfo.name + ' - 课程表' : '课程表' }}</text>
        <text class="date-range">{{ dateRangeText }}</text>
        <text v-if="classInfo.grade" class="class-grade">{{ classInfo.grade }}</text>
      </view>
      <view class="nav-section" @click="nextWeek">
        <text>下一周排课</text>
        <uni-icons type="right" size="20" color="#666666" />
      </view>
    </view>
    <!-- 课程表主体 -->
    <view class="table-container">
      <view class="table-header">
        <view class="th">日期</view>
        <view class="th">时间段</view>
        <view class="th">上课下课时间</view>
        <view class="th">教室</view>
        <view class="th">课程</view>
        <view class="th">讲师</view>
      </view>
      <scroll-view
        scroll-y
        class="table-content"
        @refresherrefresh="onRefresh"
        :refresher-enabled="true"
        :refresher-triggered="isRefreshing"
      >
        <view
          v-for="(course, index) in coursesData"
          :key="index"
          :class="['table-row', { 'row-highlight': index % 2 === 0 }]"
        >
          <view class="td">{{ course.date }}</view>
          <view class="td">{{ course.period }}</view>
          <view class="td">{{ course.time }}</view>
          <view class="td">{{ course.classroom }}</view>
          <view class="td">{{ course.name }}</view>
          <view class="td">{{ course.teacher }}</view>
        </view>
        <view v-if="coursesData.length === 0" class="no-data">
          <text>暂无课程数据</text>
        </view>
      </scroll-view>
    </view>
  </view>
</template>
<script setup>
import { ref, onMounted, computed } from 'vue';

// 获取页面参数
const pages = getCurrentPages();
const currentPage = pages[pages.length - 1];
const options = currentPage.options || {};

// 班级信息
const classInfo = ref({
	id: parseInt(options.classId) || null,
	name: decodeURIComponent(options.className || ''),
	grade: decodeURIComponent(options.classGrade || '')
});

const isRefreshing = ref(false);
const coursesData = ref([]);

// 当前周偏移量（0表示本周，-1表示上周，1表示下周）
const weekOffset = ref(0);

// 计算当前显示的日期范围文本
const dateRangeText = computed(() => {
  const today = new Date();
  const currentDayOfWeek = today.getDay();
  const monday = new Date(today);
  monday.setDate(today.getDate() - (currentDayOfWeek === 0 ? 6 : currentDayOfWeek - 1) + weekOffset.value * 7);
  
  const friday = new Date(monday);
  friday.setDate(monday.getDate() + 4);
  
  const formatDate = (date) => {
    const month = date.getMonth() + 1;
    const day = date.getDate();
    return `${month}月${day}日`;
  };
  
  return formatDate(monday) + ' ~ ' + formatDate(friday);
});

// 时间段数据
const timeSlots = ref([
  { period: '第1节', time: '8:00-8:45' },
  { period: '第2节', time: '8:55-9:40' },
  { period: '第3节', time: '10:00-10:45' },
  { period: '第4节', time: '10:55-11:40' },
  { period: '第5节', time: '14:00-14:45' },
  { period: '第6节', time: '14:55-15:40' },
  { period: '第7节', time: '16:00-16:45' },
  { period: '第8节', time: '16:55-17:40' },
  { period: '第9节', time: '19:00-19:45' },
  { period: '第10节', time: '19:55-20:40' },
]);

// 根据班级ID获取课程数据
const getClassCourses = (classId) => {
  // 根据不同班级返回不同的课程数据
  const allClassCourses = {
    1: [ // Java企业级开发班
      {
        name: 'Java基础',
        location: 'A301',
        teacher: '陈老师',
        duration: 2,
        bgColor: '#E8F4FF',
        isActive: true
      },
      {
        name: 'Spring框架',
        location: 'A302',
        teacher: '陈老师',
        duration: 2,
        bgColor: '#FFF0F5',
        isActive: false
      },
      {
        name: '数据库设计',
        location: 'B201',
        teacher: '张老师',
        duration: 3,
        bgColor: '#F0FFF0',
        isActive: false
      }
    ],
    2: [ // Python数据分析班
      {
        name: 'Python基础',
        location: 'B301',
        teacher: '林老师',
        duration: 2,
        bgColor: '#E8F4FF',
        isActive: true
      },
      {
        name: '数据分析',
        location: 'B302',
        teacher: '林老师',
        duration: 2,
        bgColor: '#FFF0F5',
        isActive: false
      },
      {
        name: '机器学习',
        location: 'C201',
        teacher: '王老师',
        duration: 3,
        bgColor: '#F0FFF0',
        isActive: false
      }
    ]
  };
  
  return allClassCourses[classId] || [
    {
      name: '通用课程',
      location: 'A101',
      teacher: '教师',
      duration: 2,
      bgColor: '#E8F4FF',
      isActive: true
    }
  ];
};

// 课程数据
const courses = ref(getClassCourses(classInfo.value.id));

// 获取课程表数据
const fetchScheduleData = () => {
  uni.showLoading({
    title: '加载中...'
  });
  
  // 计算当前周的周一和周五
  const today = new Date();
  const currentDayOfWeek = today.getDay();
  const monday = new Date(today);
  monday.setDate(today.getDate() - (currentDayOfWeek === 0 ? 6 : currentDayOfWeek - 1) + weekOffset.value * 7);
  
  const friday = new Date(monday);
  friday.setDate(monday.getDate() + 4);
  
  // 格式化日期为月日形式，例如901表示9月1日
  const formatDateDay = (date) => {
    const month = date.getMonth() + 1;
    const day = date.getDate();
    return month * 100 + day;
  };
  
  const startDateDay = formatDateDay(monday);
  const endDateDay = formatDateDay(friday);

  // 使用 uni.request 发送请求，使用回调方式避免Promise相关问题
  uni.request({
    url: 'http://127.0.0.1:9002/schedule/getScheduleByDateDayRange',
    method: 'GET',
    data: {
      startDateDay: startDateDay,
      endDateDay: endDateDay,
      classId: classInfo.value.id || null // 传递班级ID用于过滤
    },
    success: (res) => {
      console.log('获取课程表数据成功:', res);
      // 检查返回数据是否为数组
      if (res.data && Array.isArray(res.data)) {
        // 映射接口返回的数据字段到课程表上
        coursesData.value = res.data.map(item => ({
          date: item.date,
          period: item.times,
          time: item.classTimeOn + ' ~ ' + item.classTimeEnd,
          classroom: item.classRoon,
          name: item.couse,
          teacher: item.lecturer
        }));
      } else {
        // 如果不是数组，显示错误提示
        console.warn('返回数据格式不正确，期望数组格式:', res.data);
        uni.showToast({
          title: '数据格式错误',
          icon: 'none'
        });
      }
    },
    fail: (err) => {
      console.error('获取课程表失败:', err);
      uni.showToast({
        title: '获取数据失败',
        icon: 'none'
      });
    },
    complete: () => {
      uni.hideLoading();
    }
  });
};

const prevWeek = () => {
  weekOffset.value--;
  uni.showToast({
    title: '正在加载上周课表',
    icon: 'loading',
    duration: 1000
  });
  fetchScheduleData();
};

const nextWeek = () => {
  weekOffset.value++;
  uni.showToast({
    title: '正在加载下周课表',
    icon: 'loading',
    duration: 1000
  });
  fetchScheduleData();
};

const onRefresh = () => {
  isRefreshing.value = true;
  fetchScheduleData();
  setTimeout(() => {
    isRefreshing.value = false;
  }, 1000);
};

onMounted(() => {
  fetchScheduleData();
});
</script>
<style>
page {
  height: 100%;
}

.schedule-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #FFFFFF;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background-color: #FFFFFF;
  border-bottom: 1px solid #EEEEEE;
}

.nav-section {
  display: flex;
  align-items: center;
  gap: 10rpx;
  color: #666666;
  font-size: 14px;
}

.title-section {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.main-title {
  font-size: 18px;
  font-weight: bold;
  color: #333333;
  margin-bottom: 10rpx;
}

.date-range {
  font-size: 12px;
  color: #666666;
}

.class-grade {
  font-size: 12px;
  color: #1976d2;
  background-color: rgba(25, 118, 210, 0.1);
  padding: 2px 8px;
  border-radius: 10px;
  margin-top: 5px;
}

.week-info {
  font-size: 16px;
  color: #333333;
  font-weight: bold;
}

.header-icons {
  display: flex;
  align-items: center;
}

.settings-icon {
  margin-left: 30rpx;
}

.table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.table-header {
  display: flex;
  background-color: #FF3B30;
  color: #FFFFFF;
  font-size: 14px;
  font-weight: bold;
}

.table-content {
  flex: 1;
  padding: 0 20rpx;
}

.th, .td {
  flex: 1;
  padding: 20rpx;
  text-align: center;
}

.table-row {
  display: flex;
  border-bottom: 1px solid #EEEEEE;
}

.row-highlight {
  background-color: #FFF9F2;
}

.td {
  font-size: 14px;
  color: #333333;
}

.no-data {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100rpx;
  color: #999999;
  font-size: 14px;
}
</style>